package string.ReplaceStr;

/**
 * @ClassName ReplaceStr
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-22 10:20
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class ReplaceStr {
    /**
     * 剑指 Offer 05. 替换空格
     * 请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
     * <p>
     * <p>
     * <p>
     * 示例 1：
     * <p>
     * 输入：s = "We are happy."
     * 输出："We%20are%20happy."
     */

    public String replaceString(String s) {

        if (s == null) {
            return null;
        }
        if (s.length() == 0) {
            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                stringBuilder.append("%20");
            } else {
                stringBuilder.append(c);
            }
        }
        return stringBuilder.toString();//转换成string
    }


    public String replaceString1(String s) {

        if (s == null || s.length() == 0) {
            return s;
        }
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                count += 2;
            }
        }
        int right = s.length() + count - 1;
        int left = s.length() - 1;
        char[] newChars = new char[right + 1];
        while (left >= 0) {

            if (s.charAt(left) == ' ') {
                newChars[right--] = '0';
                newChars[right--] = '2';
                newChars[right] = '%';
            } else {
                newChars[right] = s.charAt(left);
            }
            right--;
            left--;
        }
        return new String(newChars);
    }


    public static void main(String[] args) {
        ReplaceStr replaceStr = new ReplaceStr();
        String str = "We are happy.";
        String string = replaceStr.replaceString1(str);
        System.out.println(string);
    }
}